import postcss from 'postcss';
import { postcssWX2ui } from "../plugin";
import postscss from 'postcss-scss';

const tagSelectors2 = [
    'ui-accordion',
    'ui-badge',
    'ui-blur',
    'ui-calendar',
    'ui-calendar1',
    'ui-cascader',
    'ui-check-list',
    'ui-count-down',
    'ui-count-up',
    'ui-divider',
    'ui-fixed-view',
    'ui-index-list',
    'ui-mask',
    'ui-mini-star',
    'ui-nav-bar',
    'ui-popover',
    'ui-popup',
    'ui-roller',
    'ui-roller-item',
    'ui-row-list',
    'ui-ruler',
    'ui-segment',
    'ui-segment-item',
    'ui-slider',
    'ui-star',
    'ui-stepper',
    'ui-sticky',
    'ui-summary',
    'ui-swipe-out',
    'ui-tab',
    'ui-tabs',
    'ui-tags',
    'ui-timeline',
    'ui-timeline-item',
    'ui-v-calendar',
    'ui-v-tab',
    'ui-v-tabs',
    'ui-w-calendar'
];

export class WxStyle {
    dom: any;
    constructor(public source: string, public isApp?: Boolean | undefined) {
    }

    async generator() {
        let code = this.source;
        code = this.transformSelectors(code);
        code = await this.removeUselessRules(code);
        if (this.isApp) {
            code = code.replace(/@import.*;\n/g, '');
            code = `@import './static/styles/index.less';\n` + code;
        }
        return code;
    }

    transformSelectors(code: string) {
        return code.replace(/(ui(-[\w]+)+)/g, ($1, $2) => {
            if (tagSelectors2.indexOf($2) > -1) {
                return '.' + $2;
            }
            return $1;
        });
    }

    async removeUselessRules(code: string) {
        code = code.replace(/(\.mix.*;)/g, '/***###$1###***/');
        code = await postcss([
            postcssWX2ui
        ]).process(code, {
            parser: postscss.parse,
        }).then(result => result.css);

        return code.replace(/(\/[*]{3}[#]{3})|([#]{3}[*]{3})\//g, '');
    }
}
